package com.bsj.travel.process.handle.service.impl;

import com.alibaba.fastjson2.JSON;
import com.bsj.consumerQ.function.HandleRun;
import com.bsj.travel.def.common.DTO.mqtt.MqttEvent;
import com.bsj.travel.enums.MqttEventEnum;
import com.bsj.travel.process.config.PublicTopicConfig;
import com.bsj.travel.process.handle.service.BasicTopicMessageService;
import com.bsj.travel.process.handle.service.BlueprintTopicMessageService;
import com.bsj.travel.process.handle.service.CustomTopicMessageService;
import com.bsj.travel.util.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author yinhao
 * @version 1.0
 * @description 默认设备数据处理
 * @date 2024/1/16
 */
@Service
@Slf4j
public class DefaultMessageHandleRun implements HandleRun {

    private static final String TSL_IDENT = "\\$\\{tsl.event.identifier\\}";

    @Autowired
    private BasicTopicMessageService basicTopicMessageService;

    @Autowired
    private BlueprintTopicMessageService blueprintTopicMessageService;

    @Autowired
    private CustomTopicMessageService customTopicMessageService;

    @Autowired
    private PublicTopicConfig topicConfig;

    @Override
    public void doRun(List<byte[]> list) {
        for (byte[] bytes : list) {
            try {
                //将内容处理成MqttEvent对象，然后根据基础通信类，物模型类，自定义类进行对应的逻辑处理
                String message = new String(bytes);
                MqttEvent event = JSON.parseObject(message, MqttEvent.class);
                changeEvent(topicConfig, event);
                MqttEventEnum eventEnum = MqttEventEnum.getMqttEventEnum(event.getEvent());
                log.info("默认设备上行消息处理: {}", JSON.toJSONString(event));
                switch (Objects.requireNonNull(eventEnum)) {
                    //OTA升级[基础通信类]
                    //NTP时钟同步[基础通信类]
                    //影子[基础通信类]
                    case OTA:
                    case NTP:
                    case SHADOW:
                        basicTopicMessageService.doPush(JSON.toJSONBytes(event));
                        break;
                    //属性上报[物模型]
                    //属性设置[物模型]
                    //事件上报[物模型]
                    case ATTRIBUTE:
                    case SETATTR:
                    case SETEVENT:
                        blueprintTopicMessageService.doPush(JSON.toJSONBytes(event));
                        break;
                    //自定义主题
                    case CUSTOMIZE:
                        customTopicMessageService.doPush(JSON.toJSONBytes(event));
                        break;
                    default:
                }
            } catch (Exception e) {
                log.error("默认设备数据处理JSON转换异常: {}", ExceptionUtil.getStackStr(e));
                continue;
            }
        }
        //保存设备上行数据量
    }

    /**
     * 处理主题类型，转换成MqttEventEnum中的属性
     * @param topicConfig
     * @param mqttEvent
     */
    private static void changeEvent(PublicTopicConfig topicConfig, MqttEvent mqttEvent) {
        String topic = mqttEvent.getTopic();
        String client = mqttEvent.getClient();
        String[] split = client.split("&");
        String productKey = split[1];
        String deviceName = split[0];
        //将主题信息还原回通用主题
        String commonTopic = topic.replaceAll(productKey, "\\$\\{productKey\\}").replaceAll(deviceName,"\\$\\{deviceName\\}");
        if (topicConfig.getShadow().contains(commonTopic)) {
            mqttEvent.setEvent(MqttEventEnum.SHADOW.name());
        } else if (topicConfig.getOta().contains(commonTopic)) {
            mqttEvent.setEvent(MqttEventEnum.OTA.name());
        } else if (topicConfig.getNtp().contains(commonTopic)) {
            mqttEvent.setEvent(MqttEventEnum.NTP.name());
        } else if (topicConfig.getAttribute().contains(commonTopic)) {
            mqttEvent.setEvent(MqttEventEnum.ATTRIBUTE.name());
        } else if (topicConfig.getSetattr().contains(commonTopic)) {
            mqttEvent.setEvent(MqttEventEnum.SETATTR.name());
        } else if (commonTopic.startsWith(topicConfig.getSetevent().get(0)
                .split(TSL_IDENT)[0])) {
            mqttEvent.setEvent(MqttEventEnum.SETEVENT.name());
        } else {
            //如果不是公共主题，那就归类为自定义主题
            mqttEvent.setEvent(MqttEventEnum.CUSTOMIZE.name());
        }
    }

    public static void main(String[] args) {
        PublicTopicConfig topicConfig = new PublicTopicConfig();
        topicConfig.setShadow(List.of("/shadow/update/${productKey}/${deviceName}"));
        topicConfig.setOta(List.of("/ota/device/inform/${productKey}/${deviceName}"));
        topicConfig.setNtp(List.of("/ext/ntp/${productKey}/${deviceName}/request"));
        topicConfig.setAttribute(List.of("/sys/${productKey}/${deviceName}/thing/event/property/post"));
        topicConfig.setSetattr(List.of("/sys/${productKey}/${deviceName}/thing/service/property/set"));
        topicConfig.setSetevent(List.of("/sys/${productKey}/${deviceName}/thing/event/${tsl.event.identifier}/post"));
        MqttEvent mqttEvent = new MqttEvent();
        mqttEvent.setClient("test001&b1ququ9io");
        mqttEvent.setTopic("/b1ququ9io/test001/update");
        changeEvent(topicConfig, mqttEvent);
        System.out.println(mqttEvent.toString());
    }
}
